package com.example.demo.service.lmp;

import com.example.demo.model.User;
import com.example.demo.service.IRedisOnlineService;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisOnlineServiceImpl implements IRedisOnlineService {

    //在线用户key前缀
    private static final String ONLINE_USERS_KEY ="chat:online_users";

    @Autowired
    private RedisTemplate<String ,String > redisTemplate;

    /*
    用户服务
     */
    @Autowired
    private IUserService userService;
    @Override
    public void loginUser(String userId) {
      User detail = userService.detail(userId);
      if(detail==null){
          return;
      }
      //获取用户姓名，组装redis要保存的值
        //id1111::张三
      String redisValue =userId + "::" +detail.getName();
      //将在线用户存到redis 一个set里面
      redisTemplate.opsForSet().add(ONLINE_USERS_KEY,userId);
      //在一天没有用户登录的时候，清空在线用户列表，设置key过期时间为1天
      redisTemplate.expire(ONLINE_USERS_KEY,1, TimeUnit.DAYS);

    }

    @Override
    public void logout(String userId) {
        //redis移除指定set值（KEY为"chat:online_users"）
        redisTemplate.opsForSet().remove(ONLINE_USERS_KEY,userId);

    }

    @Override
    public Set<String> getOnlineUser() {
        //返回redis在线用户列表的数组
        return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
    }
}
